<template>
  <div class="token-input-people" ref="tokenInputSelectedDiv">
    <a-select
      id="tokenInputSelected"
      mode="multiple"
      dropdownMatchSelectWidth="false"
      label-in-value
      ref="tokenInputSelected"
      :max-tag-count="maxTagCount"
      :value="tokenInputSelectedItems"
      :maxTagPlaceholder="maxTagPlaceholderHandel"
      :placeholder="placeholder"
      :default-value="[]"
      :filter-option="false"
      @deselect="deleteUser"
      @change="handleChange"
      @inputKeydown="inputKeydown"
      @search="fetchUser"
      @dropdownVisibleChange="openDropdown"
      style="width: 100%; vertical-align: middle">
      <a-select-option v-for="item in tokenInputSelectList" :key="item.k">
        {{ item.v }}
      </a-select-option>
    </a-select>
    <a-tooltip placement="bottom" :title="$i18n('org.index.select.people.label.js')">
      <a-button class="select-btn" type="link" @click="selectPeopleOnclick">
        <icon-font type="cap-icon-xuanren" />
      </a-button>
    </a-tooltip>
  </div>
</template>

<script>
  import api from '@/api';
  import emitter from '@/plugins/global-callback';
  import Vue from 'vue';
  import globalMethods from '@/plugins/methods';
  import { mapActions, mapState } from 'pinia';
  import { useBaseInfoStore } from '@/store/modules/base-info';

  export default {
    //快速选人组件
    name: 'TokenInputPeople',
    props: {
      placeholder: {
        type: String
      }
    },
    data: () => ({
      //快速选人可选内容
      tokenInputSelectList: [],
      //快速选人选中元素内容
      tokenInputSelectedItems: [],
      //快速选人销毁状态，编辑流程后就不能再使用了
      tokenInputDestroy: false,
      //是否输入检索选人方式
      tokenInputFetch: false,
      //缓存最近联系人列表
      recentMemberList: [],
      //最多显示多少选人
      maxTagCount: 99,
      //选人组件选人模式 流程类型,默认1并发 并发，串发； 多层 快速录入不支持
      tokenFlowType: '1'
    }),
    computed: {
      ...mapState(useBaseInfoStore, ['processSelectItems', 'baseInfo'])
    },
    created() {
      this.api = api;
      //记录选人key集合
      this.tokenInputSelectedKeys = new Set();
      //订阅快速选人输入事件
      emitter.subscribe('takenInputPeople', this.inputSelectUser);
      //限制状态
      this.maxTagLimit = false;
      this.bindOnce = false;
      this.oldWidth = 0;
      this.scrollNode = {};
      this.deleteAction = false;

      //自动调整最大tag数量限制
      this.autoMaxTagFn = globalMethods.debounce(() => {
        // const { width } = entry.contentRect;
        if (this.tokenInputSelectedItems.length === 0) {
          return;
        }
        //宽度不变，首次换行抖动
        let clientWidth = this.$el.clientWidth - 0;
        if (this.oldWidth !== null && clientWidth === this.oldWidth) {
          return;
        }
        console.log('autoMaxTagFn:0+', clientWidth);
        // 边距+图标多余的宽度 54
        let countWidth = 64;
        let liWidth = 61 + 2;
        //计算是否需要调整
        // let elementsByTagName = this.scrollNode.querySelector('ul').getElementsByTagName('li');
        for (let i = 0; i < this.tokenInputSelectedItems.length; i++) {
          let item = this.tokenInputSelectedItems[i];
          let itemWidth = this.selectedItemWidthMap[item.label];
          liWidth += itemWidth;
          liWidth += 4;
          // let number = Math.abs(liWidth - clientWidth);
          // 不是最后一个 需要考虑 countWidth
          if (i !== this.tokenInputSelectedItems.length - 1) {
            if (liWidth + countWidth > clientWidth) {
              //根据实际情况重新设置
              this.maxTagCount = i;
              console.log('autoMaxTagFn:1+' + i, liWidth);
              console.log('autoMaxTagFn:2+' + i, this.maxTagCount);
              this.$refs.tokenInputSelected.maxTagCount = this.maxTagCount;
              this.oldWidth = clientWidth;
              return;
            }
          } else {
            if (liWidth > clientWidth) {
              //根据实际情况重新设置
              this.maxTagCount = i;
              console.log('autoMaxTagFn:1+' + i, liWidth);
              console.log('autoMaxTagFn:2+' + i, this.maxTagCount);
              this.$refs.tokenInputSelected.maxTagCount = this.maxTagCount;
              this.oldWidth = clientWidth;
              return;
            }
          }
        }
        //有空余位置
        this.maxTagCount = undefined;
        this.oldWidth = clientWidth;
      }, 200);
      //选人组件返回的结果
      this.selectPeopleResultMap = new Map();
    },
    watch: {
      tokenInputSelectedItems() {
        //刷新pina 选人信息
        this.updateProcessSelectItems(this.tokenInputSelectedItems);
        this.initSelectedItemsWidth();
      },
      maxTagCount(nv) {
        console.log('选人修改1', nv);
      }
    },
    mounted() {
      this.api.tokenInput().then((res) => {
        if (!res || typeof res !== 'object') {
          return;
        }
        this.tokenInputSelectList.push(...res);
        this.recentMemberList.push(...res);
      });
      // 初始化ResizeObserver
      // this.oldWidth = this.$refs.tokenInputSelected.$el.clientWidth;
      new ResizeObserver((entries) => {
        this.autoMaxTagFn && this.autoMaxTagFn();
      }).observe(this.$el);
      //用于流程校验后弹窗选人
      emitter.subscribe('newCol_selectPeopleOnclick', () => this.selectPeopleOnclick());
    },
    updated() {
      // Vue.nextTick(() => {
      //   if (!this.bindOnce && this.$refs.tokenInputSelected) {
      //     this.scrollNode = this.$refs.tokenInputSelected.$el.firstElementChild;
      //     console.log(this.scrollNode);
      //     new ResizeObserver(() => {
      //       this.autoMaxTagFn();
      //     }).observe(this.$refs.tokenInputSelected.$el);
      //     this.oldWidth = this.$refs.tokenInputSelected.$el.clientWidth;
      //     this.bindOnce = true;
      //   }
      // });
    },
    methods: {
      ...mapActions(useBaseInfoStore, ['updateProcessSelectItems']),
      maxTagPlaceholderHandel() {
        let count = 0;
        if (this.maxTagCount < this.tokenInputSelectedItems.length) {
          count = this.tokenInputSelectedItems.length - this.maxTagCount;
        }
        const otherItems = this.tokenInputSelectedItems.slice(this.maxTagCount);
        const title = otherItems.map((el) => el.label).join(',');
        if (count > 99) count = 99;
        return <div title={title}>+ {count} ...</div>;
      },
      initSelectedItemsWidth() {
        let ctx = this.getCtx();
        let { tokenInputSelectedItems } = this;
        this.selectedItemWidthMap = this.selectedItemWidthMap || {};
        tokenInputSelectedItems.forEach((item) => {
          let label = item.label;
          if (!this.selectedItemWidthMap[label]) {
            // 7.7738 ant组件产生的dom偏差
            let textWidth = ctx.measureText(label).width;
            this.selectedItemWidthMap[label] = textWidth + 32;
          }
        });
        console.log(this.selectedItemWidthMap);
      },
      getCtx() {
        if (this.ctx) {
          return this.ctx;
        }
        let canvas = document.createElement('canvas'); //首先创建一个canvas标签
        let ctx = canvas.getContext('2d'); //把canvas的画笔给调出来
        ctx.font =
          'normal normal 400 14px Arial, "PingFang SC", "Microsoft YaHei", Helvetica, sans-serif, "SimSun"';
        this.ctx = ctx;
        return this.ctx;
      },
      handleChange(value) {
        value = value.map((el) => {
          return { key: el.key, label: el.label.trim() };
        });
        this.tokenInputSelectList = [];
        //不输入的时候还原
        this.tokenInputSelectList.push(...this.recentMemberList);
        this.add2SelectedItems(value);
        // 触发计算 如果没设置,每次变化都要重新计算
        this.oldWidth = null;
        this.autoMaxTagFn();
      },
      handleClick() {
        this.$emit('click-input');
      },
      add2SelectedItems(value) {
        this.tokenInputSelectedItems = value;
        if (this.tokenInputSelectedKeys.size > this.tokenInputSelectedItems.length) {
          this.tokenInputSelectedKeys.clear();
        }
        this.tokenInputSelectedItems.forEach((item) => this.tokenInputSelectedKeys.add(item.key));
      },
      //输入搜索用户
      fetchUser(value) {
        console.log('search-fetchUser',value)
        if (this.keyBoardPaste){
          this.pasteUser(value);
          return;
        }
        if (!this.tokenInputFetch) {
          this.tokenInputFetch = true;
          api
            .tokenInputSearch(value)
            .then((res) => {
              if (!res || typeof res !== 'object') {
                return;
              }
              this.tokenInputSelectList = [];
              this.tokenInputSelectList.push(...res);
            })
            .finally(() => (this.tokenInputFetch = false));
        }
      },
      //复制粘贴搜索多个用户
      pasteUser(value){
        console.log('search-fetchUser-pasteUser',value)
        if (!this.tokenInputFetch) {
          this.tokenInputFetch = true;
          api
            .tokenInputFromCopy(value)
            .then((res) => {
              if (!res || typeof res !== 'object') {
                return;
              }
              this.inputSelectUser(res)
            })
            .finally(() => {
              this.$refs.tokenInputSelected.blur();
              this.tokenInputFetch = false;
              this.keyBoardPaste = false;
            });
        }
      },
      /**
       * 插入选择的用户数据
       * */
      inputSelectUser(selectedUsers) {
        if (!selectedUsers || this.tokenInputDestroy) {
          return;
        }
        //去重复，重复添加的没必要
        let map = selectedUsers
          .filter((item) => item.k && !this.tokenInputSelectedKeys.has(item.k))
          .map((item) => {
            return {
              key: item.k,
              label: item.v
            };
          });
        this.tokenInputSelectedItems.push(...map);
        this.add2SelectedItems(this.tokenInputSelectedItems);
      },
      deleteUser(value) {
        this.deleteAction = true;
        console.log('deleteUser', value);
      },
      // 流程选人
      selectPeopleOnclick() {
        const flowtype = {
          0: 'sequence',
          1: 'concurrent',
          2: 'multiple'
        };
        $.selectPeople({
          type: 'selectPeople',
          panels:
            'OcipOrganization,Department,BusinessDepartment,Team,Post,Outworker,RelatePeople,JoinOrganization,OrgMetadataTag',
          selectType:
            'Account,Department,Team,Post,Outworker,RelatePeople,Member,BusinessDepartment,BusinessAccount,OrgMetadataTag',
          text: this.$i18n('workflow.insertPeople.urgerAlt'),
          showFlowTypeRadio: true,
          hiddenColAssignRadio: true,
          hiddenMultipleRadio: false,
          flowtype: flowtype[this.tokenFlowType] || 'concurrent',
          maxSize: 100,
          isConfirmExcludeSubDepartment: true,
          unallowedSelectEmptyGroup: true,
          accessFileSecretLevel: this.baseInfo.secretLevel.value,
          memberWithDeptInfo: true,
          excludeElementsBeyondMemberSize: 'Department|3000,Post|3000,Team|3000,Level|3000',
          params: {
            value: this.tokenInputSelectedItems
              .map((item) => item.key.split('|').slice(0, 2).join('|'))
              .join(',')
          },
          callback: (res) => {
            console.log('token-input-people result =',res);
            if (res.obj && res.obj[0].length) {
              let [selected = [], tokenFlowType = '1'] = res.obj;
              this.selectPeopleResultMap.clear();
              this.tokenInputSelectedItems = selected.map((item) => {
                let key = `${item.type}|${item.id}|${item.loginAccountId}`;
                if (item.type !== 'Member') {//非人员类型进行缓存
                  this.selectPeopleResultMap.set(key,item);
                }
                return {
                  label: item.memberName || item.name,
                  key: key
                };
              });
              this.tokenFlowType = tokenFlowType;
              this.tokenInputSelectList = [];
              this.tokenInputSelectList.push(...this.recentMemberList);
              // 触发计算 如果没设置,每次变化都要重新计算
              this.initSelectedItemsWidth();
              this.oldWidth = null;
              this.autoMaxTagFn();
              //触发选人完毕事件
              this.$emit('afterSelectPeople',{tokenFlowType});
            }
          }
        });
      },
      openDropdown(open) {
        this.$emit('changeActive', open);
      },
      inputKeydown(keyEvent){
        if (keyEvent.ctrlKey && keyEvent.key === 'v'){
          //复制粘贴事件
          this.keyBoardPaste = true;
          console.log('inputKeydown',keyEvent);
        }
      },
      /*获取快速选人的结果*/
      async findSelectPeopleEntities() {
        //快速选人的
        let result = this.tokenInputSelectedItems.map(({key}) => this.selectPeopleResultMap.get(key))
          .filter(item => item);
        //用户手动输入的
        let parseEntities = this.tokenInputSelectedItems.filter(({key}) => !this.selectPeopleResultMap.has(key))
          .map((item) => {
            let array = item.key.split('|');
            return `${array[0]}|${array[1]}`;
          });
        if (parseEntities.length) {
          let parseObj = await api.tokenInputParse({value: parseEntities.join(',')});
          parseObj.entities.forEach((item) => {
            item.departmentId = item.deptId;
            result.push(item);
          });
        }
        return result;
      }
    }
  };
</script>

<style lang="scss">
  .token-input-people {
    white-space: nowrap;
    flex: 1;
    display: flex;
    position: relative;

    .select-btn {
      position: absolute;
      right: 5px;
      color: #1890ff;
      color: var(--theme-brand6,#1890ff);
      &:hover {
        color: #40a9ff;
        color: var(--theme-brand4, #40a9ff);
      }
    }

    div.ant-select-selection--multiple {
      max-height: 33px;
      overflow-y: hidden;
    }

    // 重要两行
    .ant-select-selection--multiple .ant-select-selection__rendered {
      max-height: 33px;
    }
  }
</style>
